﻿using HZY.Quartz.Common;
using HZY.Quartz.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;

namespace HZY.Quartz.Filter
{
    /// <summary>
    /// Action 授权 检查
    /// </summary>
    public class AppAuthorizationAttribute : ActionFilterAttribute
    {

        /// <summary>
        /// 执行 Action 之前执行
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //var routeValues = context.ActionDescriptor.RouteValues;
            //var areaName = routeValues["area"];
            //var controllerName = routeValues["controller"];
            //var actionName = routeValues["action"];

            var httpContext = context.HttpContext;
            var configuration = httpContext.RequestServices.GetService(typeof(IConfiguration)) as IConfiguration;
            var tokenKey = configuration[AppConsts.TokenKeyName];
            var tokenValue = configuration[AppConsts.TokenValueName];

            var token = httpContext.Request.Headers[tokenKey].ToString();

            if (string.IsNullOrWhiteSpace(token) || httpContext.User.Identity == null || httpContext.User.Identity.Name != tokenValue)
            {
                var apiResult = ApiResult.ResultMessage(ApiResult.ApiResultCodeEnum.UnAuth, AppConsts.UnAuth);
                context.Result = new JsonResult(apiResult);
                return;
            }
        }
    }
}
